package item30;

import java.util.HashMap;
import java.util.Map;

// enum type with constant-specific class bodies and data
// 具有常量特定方法的枚举类型
public enum Operation03 {

    PLUS("+"){
        @Override
        double apply(double x, double y) {
            return x + y;
        }
    },
    MINUS("-"){
        @Override
        double apply(double x, double y) {
            return x - y;
        }
    },
    TIMES("*") {
        @Override
        double apply(double x, double y) {
            return x * y;
        }
    },
    DIVIDE("/") {
        @Override
        double apply(double x, double y) {
            return x / y;
        }
    };



    private final String symbol;

    Operation03(String symbol) {
        this.symbol = symbol;
    }

    @Override
    public String toString() {
        return symbol;
    }

    abstract double apply(double x, double y);

    // implementing a fromString method on an enum type
    // 在枚举类型上实现fromString方法
    private static final Map<String, Operation03> stringToEnum = new HashMap<>();

    static {
        // initialize map from constant name to enum constant
        // 把操作放入map中key为操作符字符串，value是操作符
        for (Operation03 op : values())
            stringToEnum.put(op.toString(), op);
    }

    // returns operation for string, or null if String is invalid
    // 根据操作符字符串
    public static Operation03 fromString(String symbol) {
        return stringToEnum.get(symbol);
    }

}
